package com.anandsoftware.security.impl;

import java.security.MessageDigest;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.anandsoftware.security.AbstractSecurityAlgorithm;

public class TrippleDES extends AbstractSecurityAlgorithm {

	/**
	 * @param plainText
	 *            text to encrypt
	 * @return hex representation of a encrypted text
	 */
	@Override
	public String encrypt(String plainText) {
		try {
			final MessageDigest md = MessageDigest.getInstance("md5");
			final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
					.getBytes("utf-8"));
			final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
			for (int j = 0, k = 16; j < 8;) {
				keyBytes[k++] = keyBytes[j++];
			}

			final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
			final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
			final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, key, iv);

			final byte[] plainTextBytes = plainText.getBytes("utf-8");
			final byte[] cipherText = cipher.doFinal(plainTextBytes);
			return byteArray2Hex(cipherText);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * @param encryptedText
	 *            text to decrypt.
	 * @return hex representation of a decrypted string.
	 */

	@Override
	public String decrypt(String encryptedText) {
		try {
			final MessageDigest md = MessageDigest.getInstance("md5");
			final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
					.getBytes("utf-8"));
			final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
			for (int j = 0, k = 16; j < 8;) {
				keyBytes[k++] = keyBytes[j++];
			}

			final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
			final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
			final Cipher decipher = Cipher
					.getInstance("DESede/CBC/PKCS5Padding");
			decipher.init(Cipher.DECRYPT_MODE, key, iv);

			// final byte[] encData = new
			// sun.misc.BASE64Decoder().decodeBuffer(message);
			final byte[] plainText = decipher
					.doFinal(hex2ByteArray(encryptedText));

			return new String(plainText, "UTF-8");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}
}
